import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_dir = r"D:\WorkSpace\qwen\Qwen2.5-3B"
tokenizer = AutoTokenizer.from_pretrained(model_dir,trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_dir,trust_remote_code=True)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)  # 确保模型被移到 GPU/CPU 上

messages = [
    {"role": "system", "content": "你是小爱同学，是一个可靠的智能酒店服务助手。接下来你将与入住酒店的客人进行交流。"}
]

# 使用Qwen生成回答
def generate_response(prompt):
    messages.append({"role":"user","content":prompt})

    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )
    model_inputs = tokenizer([text], return_tensors="pt").to(device)

    generated_ids = model.generate(
        **model_inputs,
        max_new_tokens=512
    )
    generated_ids = [
        output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
    ]

    response1 = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]

    messages.append({"role":"assistant","content":response1})

    messages.append({"role":"user","content":"上一句话最匹配以下哪个关键字，请只返回关键字内容？如果没有合适的关键字，请返回\"无关键字\"。关键字列表如下：\"房间号\"，\"打扫服务\"，\"网络服务\"，\"毛巾\"，\"洗漱用品\"，\"拖鞋\"，\"水壶\"、，\"被子\"，\"聊天\"，\"对话\"，\"预定\"，\"预约\"，\"退房\"，\"延迟退房\"，\"酒店信息\""})

    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )
    model_inputs = tokenizer([text], return_tensors="pt").to(device)

    generated_ids = model.generate(
        **model_inputs,
        max_new_tokens=512
    )
    generated_ids = [
        output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
    ]
    response2 = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]

    messages.pop()

    print(response2)
    return response1, response2

def clear_memory():
    global messages
    messages = [
        {"role": "system", "content": "你是小爱同学，是一个可靠的智能酒店服务助手。接下来你将与入住酒店的客人进行交流。"}
    ]